#ifndef PTHREAD__HPP
#define PTHREAD__HPP
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h>
#include <string>
#include <functional>

namespace pthread_module
{
    int count = 1;
    using func_t = std::function<void()>;
    class Thread
    {
    private:
        void IsDetach()
        {
            _isdetach = true;
        }
        void IsRunning()
        {
            _isrunning = true;
        }

    public:
        Thread(func_t func) : _tid(0),
                   _isdetach(false),
                   _isrunning(false),
                   _func(func)
        {
            _name += "Thread " + std::to_string(count++);
        }
        static void *Coutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->IsRunning();
            if (self->_isdetach)
                self->Detach();
            std::cout << "pthread create success " << self->_name << std::endl;
            self->_func();
            return nullptr;
        }
        bool Start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Coutine, this);
            if (n != 0)
            {
                std::cerr << "pthread create error " << _name << std::endl;
                return false;
            }
            return true;
        }
        bool Stop()
        {
            int n = pthread_cancel(_tid);
            if (n != 0)
            {
                std::cerr << "pthread_cancel error " << _name << std::endl;
                return false;
            }
            else
            {
                std::cout << "pthread_cancel success " << _name << std::endl;
            }
            return true;
        }
        bool Detach()
        {
            if(_isrunning)
            int n = pthread_detach(_tid);
            _isdetach = true;
            return true;
        }
        void Join()
        {
            if (_isdetach)
            {
                std::cerr << "线程以及被detach了,join失败 " << _name << std::endl;
                return;
            }
                
            int n = pthread_join(_tid, &_res);
            if (n != 0)
            {
                std::cerr << "pthread_join error " << _name << std::endl;
                return;
            }
            else
            {
                std::cout << "pthread_join success " << _name << std::endl;
            }
        }
        ~Thread()
        {
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isdetach;
        bool _isrunning;
        void *_res;
        func_t _func;
    };
}

#endif